﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace hello_accinv
{
    public partial class Login : Form
    {
        private Database db;

        public Login()
        {
            InitializeComponent();
            db = new Database();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            DoLogin();
        }

        private void DoLogin()
        {
            db.Insert("ActionLog", "'" + CurrentDateTime.GetDate() + "','" + CurrentDateTime.GetTime() + "','User logged in.'");
            Visible = false;
            Mainform mf = new Mainform();
            mf.SetPermission(GetPermission());    // Depends on logged-in username
            ClearLoginForm();
            if (mf.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                GC.Collect();
                mf.Dispose();

                Visible = true;
                txtboxUsername.Focus();
            }
            else
            {
                GC.Collect();
                Dispose();
            }
        }

        private int GetPermission()
        {
            try
            {
                return Int32.Parse(txtboxUsername.Text);
            }
            catch (FormatException)
            {
                return 0;
            }
        }

        private void ClearLoginForm()
        {
            txtboxUsername.Clear();
            txtboxPassword.Clear();
        }

        private void txtboxUsername_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (txtboxUsername.Text.Contains('.') && e.KeyChar == '.')
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = !Char.IsDigit(e.KeyChar) && (Keys)e.KeyChar != Keys.Back && e.KeyChar != '.';
            }

            if ((Keys)e.KeyChar == Keys.Enter)
            {
                if (txtboxUsername.Text.Length > 0 && txtboxPassword.Text.Length > 0)
                {
                    DoLogin();
                }
            }
        }

        private void txtboxPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Keys)e.KeyChar == Keys.Enter)
            {
                if (txtboxUsername.Text.Length > 0 && txtboxPassword.Text.Length > 0)
                {
                    DoLogin();
                }
            }
        }
    }
}
